//
//  HPShareDetailsViewController.m
//  fruitsDealers
//
//  Created by sgone on 16/3/24.
//  Copyright © 2016年 com.sgone. All rights reserved.
//

#import "HPShareDetailsViewController.h"
#import "HPShareDetailsTableViewCell.h"
#import "DXMessageToolBar.h"
//#import "HPHttpService.h"
#import "MJRefresh.h"
#import "HPShareDetailsHeaderView.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "AFNetworking.h"
#import "IQKeyboardManager.h"
#import "EnlargeImageViewController.h"
@interface HPShareDetailsViewController () <UITableViewDelegate, UITableViewDataSource,DXMessageToolBarDelegate,UIGestureRecognizerDelegate,ShareDetailsTableViewCellDelegate> {
    
    CGFloat cellHeight;
    CGFloat emptyCellHeight;
//    HPHttpService *service;
    int currentPage;
    int sizeCount;
    NSString *parentid;
    NSString *userName;
    NSString *parent_type;
//    IQKeyboardManager *manager2;
    
}

@property (strong, nonatomic) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) HPShareDetailsTableViewCell *cell;
//@property (nonatomic, strong) OMOrderEmptyTableViewCell *emptyCell;
@property (strong, nonatomic) DXMessageToolBar *chatToolBar;
@property (nonatomic, strong) HPShareDetailsHeaderView *headerView;
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, weak) IQKeyboardManager *manager2;

//back
@property(nonatomic,strong) UIButton *backBtn1;

@end

@implementation HPShareDetailsViewController




//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}

- (NSMutableArray *)dataArray {
    
    if (_dataArray == nil) {
        
        _dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataArray;
}


- (DXMessageToolBar *)chatToolBar
{
    if (_chatToolBar == nil) {
        
        _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight], self.view.frame.size.width, [DXMessageToolBar defaultHeight])];
        _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _chatToolBar.delegate = self;
        _chatToolBar.maxLength = 350;
        
        if ([parentid isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"wId"]]) {
            
            _chatToolBar.placeHolder = @"点击评论进行回复";
        } else
            _chatToolBar.placeHolder = @"评论";
    }
    
    return _chatToolBar;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
 
    
    [super viewDidLoad];
    
    self.backBtn.hidden = YES;
    self.titleLabel.text = @"详情";
    self.rightBut.hidden = YES;
    self.topView.hidden = NO;
    
   

    
    
    
    
    
    
    parentid = self.messageDic[@"uid"];
    parent_type = self.messageDic[@"user_type"];
    
    [self setTableView];
    
    
    
    self.backBtn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 20, 44, 44)];
    [self.backBtn1 setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.backBtn1 addTarget:self action:@selector(back2:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.backBtn1];

    
    self.manager2 = [IQKeyboardManager sharedManager];
    
    [self.view addSubview:self.chatToolBar];
    
    [self.chatToolBar.inputTextView becomeFirstResponder];
    
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidKeyBoardClick)];
//    tapGesture.numberOfTouchesRequired = 1;
//    tapGesture.numberOfTapsRequired = 1;
//    [self.view addGestureRecognizer:tapGesture];
    
    [self setupDownRefresh];
    [self setupUpRefresh];
    

//    [self getShareDetailsByPage:currentPage size:sizeCount];
}




-(void)back2:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

- (void)setTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ViewWidth, ViewHeight - 64 - self.chatToolBar.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = BACKGROUND1;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    self.tableView.estimatedRowHeight = 94.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.headerView = [[HPShareDetailsHeaderView alloc] init];
    self.headerView.delegate = self;

    
    NSString *string = self.messageDic[@"imglist"];
    
    
    if (string.length < 5) {
        
        self.headerView.images = [[NSArray alloc] init];
    }
    else
    {
        
        NSString *subString = @"|";
        self.headerView.images = [string componentsSeparatedByString:subString];
    }
    
    CGFloat headerViewHeight = [self.headerView cellHeightWithMessage:self.messageDic];
    self.headerView.frame = CGRectMake(0, 0, ViewWidth, headerViewHeight);
    self.tableView.tableHeaderView = self.headerView;
     self.headerView.delegate = self;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentToReleaserClick)];
    tapGesture.numberOfTouchesRequired = 1;
    tapGesture.numberOfTapsRequired = 1;
    [self.headerView addGestureRecognizer:tapGesture];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hideRightButton" object:nil userInfo:@{@"state":@"0"}];
    self.manager2.enable = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hideRightButton" object:nil userInfo:@{@"state":@"1"}];
    self.manager2.enable = YES;
}

- (void)getShareDetailsByPage:(int)page size:(int)size {
    
//    [MBProgressHUD showSuccess:@"正在载入评论"];
//    [MBProgressHUD  showHUDAddedTo:self.tableView animated:YES];
    NSString *urlStr = [NSString stringWithFormat:@"%@get_friend_discuss_list",SERVER_ADDRESS3];
    NSDictionary *parmas = @{@"cur_page" : [NSString stringWithFormat:@"%d",page] ,@"cur_size" : [NSString stringWithFormat:@"%d",size] ,@"fid" : self.fid };
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            NSArray *array = responseObject[@"data"][@"list"];
//            if (array.count != 0) {
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:array];
                [MBProgressHUD hideHUDForView:self.tableView animated:YES];
                [self.tableView reloadData];
        }
        else
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            [self.view makeToast:str];
       
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.view makeToast:@"请检查网络"];
        
    }];
    
    
    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        
//        [service getShareDetailsByCur_page:[NSString stringWithFormat:@"%d",page] cur_size:[NSString stringWithFormat:@"%d",sizeCount] id:self.fid success:^(NSArray *resultArray) {
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                [self.dataArray removeAllObjects];
//                [self.dataArray addObjectsFromArray:resultArray];
//                [self.tableView reloadData];
//            });
//        } error:^(NSString *errorInfo) {
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:self.navigationController];
//            });
//        }];
//    });
  
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
//    if (self.dataArray.count == 0) {
//        
//        return 1;
//    }
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    if (self.dataArray.count == 0) {
//        
//        self.emptyCell = [OMOrderEmptyTableViewCell cellWithTableView:self.tableView];
//        self.emptyCell.selectionStyle = UITableViewCellSelectionStyleNone;
//        self.emptyCell.headerViewHeight = self.headerView.height;
//        self.emptyCell.emptyLabel.hidden = YES;
//        self.emptyCell.emptyImageView.hidden = YES;
//        emptyCellHeight = [self.emptyCell setEmptyOrderCell];
//        return self.emptyCell;
//    }
    
    

//    if (self.dataArray.count != 0) {
  
    
    self.cell = [HPShareDetailsTableViewCell cellWithTableView:tableView];
 
    self.cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
//    if (self.dataArray.count != 0) {
        self.cell.messageDic = self.dataArray[indexPath.row];
    
        cellHeight = [self.cell cellHeight];

//    }
 
    
    return self.cell;
        
//    }
//    
//    
//    else
//    {
//        return self.cell;
//    
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataArray.count == 0) {
        
        return emptyCellHeight;
    }
    
    //    NSLog(@"%f",cellHeight);
    
    return cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
//    NSLog(@"wuwuuwuwu %@  %@",self.dataArray[indexPath.row][@"uid"],[self.dataHandler.userDic objectForKey:@"wId"]);
    
    parentid = self.dataArray[indexPath.row][@"uid"];
    
    if ([parentid isEqualToString:[self.dataHandler.userDic objectForKey:@"wId"]]) {
        
//        [MBProgressHUD showError:@"不能对自己进行回复和评论"];
        [self.view makeToast:@"不能对自己进行回复和评论"];
        return;
    }
    
    userName = self.dataArray[indexPath.row][@"username"];
    parent_type = self.dataArray[indexPath.row][@"user_type"];
    
    self.chatToolBar.placeHolder = [NSString stringWithFormat:@"回复：%@",userName];
}

- (void)commentToReleaserClick {
    
    parentid = self.messageDic[@"uid"];
    
//    if ([parentid isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"wId"]])
    
    if ([parentid isEqualToString:[self.dataHandler.userDic objectForKey:@"wId"]])
    {

        [self.view makeToast:@"不能对自己进行回复和评论"];
        return;
    }
    userName = self.messageDic[@"userinfo"][@"name"];
    parent_type = self.messageDic[@"user_type"];
    
    self.chatToolBar.placeHolder = @"评论";
}

- (void)hidKeyBoardClick {
    
    [self.view endEditing:YES];
}

- (void)sendMessageClick:(NSString *)text {
    
    [self.view endEditing:YES];

    
    if ([self.chatToolBar.placeHolder rangeOfString:@"评论"].location != NSNotFound) {
        
        if ([self.messageDic[@"userinfo"][@"name"] isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"wholesaler_name"]]) {
            
            [self.view makeToast:@"不能对自己进行回复和评论"];
            return;
        }
        
        parentid = @"0";
        parent_type = @"0";
    }

    __weak HPShareDetailsViewController *weakSelf = self;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@add_friend_discuss_list",SERVER_ADDRESS3];
    NSDictionary *parmas = @{@"tel" : self.dataHandler.phone , @"uid" : [self.dataHandler.userDic objectForKey:@"wId"] , @"fid" : self.fid, @"user_type" : @"3" , @"parentid" : parentid ,@"parent_type" : parent_type , @"discuss" : text };
    
    [MBProgressHUD showHUDAddedTo:weakSelf.tableView animated:YES];
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];

            [weakSelf loadNewShare];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"refreshShareListMethod" object:nil];
  
            
        }
        else
        {
        
          
        
        
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
       
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.view makeToast:@"请检查网络"];
        
    }];
    
    
    
    
//    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        
//        [service setShareCommentByFid:self.fid discuss:text parentid:parentid parent_type:parent_type success:^(NSString *resultStr) {
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                [MBProgressHUD hideAllHUDsForView:weakSelf.tableView animated:YES];
//                
//                if ([resultStr isEqualToString:@"success"]) {
//                    
//                    [MBProgressHUD showSuccess:@"发送成功"];
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshShareListMethod" object:nil];
//                    [weakSelf getShareDetailsByPage:1 size:20];
//                }
//            });
//        } error:^(NSString *errorInfo) {
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                [MBProgressHUD hideAllHUDsForView:weakSelf.tableView animated:YES];
//                [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:weakSelf.navigationController];
//            });
//        }];
//    });
}

#pragma mark - DXMessageToolBarDelegate
- (void)inputTextViewWillBeginEditing:(XHMessageTextView *)messageInputTextView{
    
}

- (void)didSendText:(NSString *)text
{
    if (text && text.length > 0) {
        [self sendMessageClick:text];
    }
}

- (void)scrollViewToBottom:(BOOL)animated
{
    if (self.tableView.contentSize.height > self.tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
        [self.tableView setContentOffset:offset animated:animated];
    }
}

#pragma mark 进行刷新

/**
 *
 *  @brief  集成下拉刷新
 */
- (void)setupDownRefresh
{
//    //1.添加刷新控件
//    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
//    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewShare)];
//    //2.进入刷新状态
//    //        [self.tableView.header beginRefreshing];
    
    
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(loadNewShare)];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中";
    
    
    
    
    
    
}

/**
 *
 *  @brief  集成上拉刷新
 */
- (void)setupUpRefresh
{
//    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShare)];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreShare)];
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.footerRefreshingText = @"正在帮你加载中";
    
    
    
}

/**
 *
 *  @brief  加载更多
 */
- (void)loadNewShare
{
    
    currentPage = 1;
    sizeCount = 20;
    [self getShareDetailsByPage:currentPage size:sizeCount];
    
    //    // 刷新表格
    [self.tableView reloadData];
    
    // 结束刷新
//    [self.tableView.header endRefreshing];
//    
//    //重置加载更多
//    [self.tableView.footer resetNoMoreData];
    
    
    [self.tableView headerEndRefreshing];
    
    
}

/**
 *
 *  @brief  加载更多
 */
- (void)loadMoreShare
{
    currentPage++;
    sizeCount = 20;

    
    
//    [self.tableView footerEndRefreshing];
//    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@get_friend_discuss_list",SERVER_ADDRESS3];
 
    NSDictionary *parmas = @{@"cur_page" : [NSString stringWithFormat:@"%d",currentPage] ,@"cur_size" : @"" ,@"fid" : self.fid };
    
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
          
            NSArray *array = responseObject[@"data"][@"list"];
            
            //            if (array.count != 0) {
            [self.dataArray addObjectsFromArray:array];
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [self.tableView footerEndRefreshing];
            [self.tableView reloadData];
          
        }
        else
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            [self.view makeToast:str];
            [self.tableView footerEndRefreshing];
        }
  
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.view makeToast:@"请检查网络"];
        [self.tableView footerEndRefreshing];
        
    }];
    

    

    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        
//        [service getShareDetailsByCur_page:[NSString stringWithFormat:@"%d",currentPage] cur_size:[NSString stringWithFormat:@"%d",sizeCount] id:self.fid success:^(NSArray *resultArray) {
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                if (resultArray.count == 0) {
//                    //没有更多的数据加载
//                    [self.tableView.footer noticeNoMoreData];
//                } else {
//                    
//                    [self.dataArray addObjectsFromArray:resultArray];
//                    [self.tableView reloadData];
//                    [self.tableView.footer endRefreshing];
//                }
//            });
//        } error:^(NSString *errorInfo) {
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
//                
//                [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:self.navigationController];
//            });
//        }];
//    });
//    
//    [self.tableView.footer noticeNoMoreData];
}



//图片放大显示
- (void)imageWithNames:(NSMutableArray *)array andIndex:(int)index

{
    
    
    NSMutableArray *zImageArray = [[NSMutableArray alloc]initWithCapacity:0];
    EnlargeImageViewController *enlargeVC = [[EnlargeImageViewController alloc] init];
    //    UIImageView *imageView = [[UIImageView alloc] init];
    
    for (int i = 0; i < array.count; i++) {
        //        [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ACURLiamge,array[i]]] placeholderImage:[UIImage imageNamed:@"timeline_image_placeholder"]];
        //        [zImageArray addObject:imageView.image];
        [zImageArray addObject:array[i]];
    }
    
    //    enlargeVC = [[EnlargeImageViewController alloc]init];
    enlargeVC.imageArray = zImageArray;
    enlargeVC.pageIndex = index - 200;
    enlargeVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;    // 设置动画效果
    //    [self presentViewController:enlargeVC animated:YES completion:nil];
    //    [self presentViewController:enlargeVC animated:YES completion:^{
    //
    //    }];
    
    [self.parentViewController.tabBarController addChildViewController:enlargeVC];
    
    [self.parentViewController.tabBarController.view addSubview:enlargeVC.view];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
